<template>
    <div class="edu-page-warp">
        <div class="edu-page-title">
            <!-- <span
                v-for="(item, index) in topNavItems"
                :class="{active: item.active}"
                :key="index"
                class="border-right"
                @click="clickItem(item)"
            >{{ item.label }}</span> -->
            <template
            >
                <el-button
                    v-if="dataType === 2"
                    type="text"
                    style="float: left;"
                    @click="exportDoc"
                >{{ $t('common.btn.export') }} DOC</el-button>
                <el-button
                    v-if="dataType === 2"
                    type="text"
                    style="float: left; margin-left: 8px;"
                    @click="exportPdf"
                >{{ $t('common.btn.export') }} PDF</el-button>
                <el-button 
                    size="mini"
                    v-if="dataType === 2"
                    style="float: right; margin-right: 8px;"
                    @click="back"
                    >返回</el-button>
            </template>
        </div>
        <div style="position:relative">
            <div v-if="dataType === 2" class="check-course">
                <el-form ref="queryForm" :model="queryForm" label-position="right" label-width="80px">
                    <el-form-item label="学期：" prop="status">
                        <el-select v-model="schoolTerm" style="width: 100%;" @change="checkCourse" clearable>
                            <el-option
                                v-for="item in semesterListMap"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-form>
            </div>
            <!-- <h2 style="text-align: center;;margin-top:15px">{{ schemeInfo.title }}</h2> -->
            <h2 v-if="focusIndex === 0" style="text-align: center;;margin-top:15px">{{ schemeInfo.name }}</h2>
            <h2 v-if="focusIndex === 1" style="text-align: center;;margin-top:15px">{{ schemeInfo.nameEn }}</h2>
            <div v-if="focusIndex === 0">
                <div v-for="(item, index) in schemeChapters" :key="index" style="padding: 24px;">
                    <div v-if="item.contentType == 1">
                         <h3 :style="{fontSize: item.fontSize + 'px'}">{{ item.name }}</h3>
                        <p style="word-break: break-all" v-html="item.content"></p>
                        <hr>
                    </div>
                    <div v-if="item.contentType == 2">
                        <h3 :style="{fontSize: item.fontSize + 'px'}">{{ item.name }}</h3>
                        <div v-if="item.detailTable">
                            <p v-html="item.detailTable.contentBefore"></p>
                            <template >
                                <courseCategoryForm
                                    v-if="item.detailTable.table === 1"
                                    :template-id="id"
                                    :culture-id="templateId"
                                    :is-read="true"
                                    :data-type="dataType"
                                    :in-change="schemeInfo.status == 5"
                                />
                                <courseForm
                                    v-else
                                    :template-id="id"
                                    :is-read="true"
                                    :data-type="dataType"
                                    :in-change="schemeInfo.status == 5"
                                    :schoolTerms="schoolTerms"
                                    :projId="projId"
                                />
                            </template>
                            <p v-html="item.detailTable.contentAfter"></p>
                        </div>
                        <hr>
                    </div>
                    <div v-if="item.contentType == 3 || item.isOldContent">
                        <h3 :style="{fontSize: item.fontSize + 'px'}">{{ item.name }}</h3>
                        <div>
                            <p v-if="item.detailTable" v-html="item.detailTable.contentBefore"></p>
                            <template>
                                <courseForm
                                    :template-id="id"
                                    :is-read="true"
                                    :data-type="dataType"
                                    :in-change="schemeInfo.status == 5"
                                    :projId="projId"
                                    :schoolTerms="schoolTerms"
                                />
                            </template>
                            <p v-if="item.detailTable" v-html="item.detailTable.contentAfter"></p>
                        </div>
                        <hr>
                    </div>
                </div>
            </div>
            <div v-if="focusIndex === 1">
                <div v-for="(item, index) in schemeChapters" :key="index" style="padding: 24px;">
                    <div v-if="item.contentType == 1">
                        <h3 :style="{fontSize: item.fontSize + 'px'}">{{ item.nameEn }}</h3>
                        <p style="word-break: break-all" v-html="item.contentEn"></p>
                        <hr>
                    </div>
                    <div v-if="item.contentType == 2">
                        <h3 :style="{fontSize: item.fontSize + 'px'}">{{ item.nameEn }}</h3>
                        <div v-if="item.detailTable">
                            <p v-html="item.detailTable.contentBeforeEn"></p>
                            <template v-if="item.detailTable.table === 1">
                                <courseCategoryForm
                                :template-id="id"
                                :culture-id="templateId"
                                :is-read="true"
                                :data-type="dataType"
                            />
                                <courseForm
                                    :template-id="id"
                                    :is-read="true"
                                    :data-type="dataType"
                                    :projId="projId"
                                    :schoolTerms="schoolTerms"
                                />
                            </template>
                            <p v-html="item.detailTable.contentAfterEn"></p>
                        </div>
                        <hr>
                    </div>
                    <div v-if="item.contentType == 3 || item.isOldContent">
                        <h3 :style="{fontSize: item.fontSize + 'px'}">{{ item.nameEn }}</h3>
                        <div>
                            <p v-if="item.detailTable" v-html="item.detailTable.contentBeforeEn"></p>
                            <template>
                                <courseForm
                                    :template-id="id"
                                    :is-read="true"
                                    :data-type="dataType"
                                    :in-change="schemeInfo.status == 5"
                                    :projId="projId"
                                    :schoolTerms="schoolTerms"
                                />
                            </template>
                            <p v-if="item.detailTable" v-html="item.detailTable.contentAfterEn"></p>
                        </div>
                        <hr>
                    </div>
                </div>
            </div>
        </div>
        <el-dialog
            :visible.sync="copyVisible"
            title="查看课程"
            width="70%"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
        >
            <el-table
            :data="courseTables"
            :height="tableHeight"
            :span-method="arraySpanMethod"
            border
            tooltip-effect="light"
        >
                <el-table-column label="课程编号" align="left"  width="90">
                    <template slot-scope="props">
                        <div v-if="props.row.isCategoryRow">
                            <el-row>
                                <el-col :span="2">
                                    <div
                                        class="float-left"
                                        style="display:inline-block;height:50px;line-height:50px;"
                                    >
                                        <i v-if="props.row.directionCode" style="margin-left:20px;">
                                            &nbsp;
                                        </i>
                                        <span>
                                            {{ props.row.sequence }}{{ props.row.categoryName }}
                                        </span>
                                    </div>
                                </el-col>
                            </el-row>
                        </div>
                        <div v-else>
                            <span>{{ props.row.code }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column min-width="150" align="center" label="课程名称"  show-overflow-tooltip>
                    <template slot-scope="props">
                        {{ props.row.name }}
                    </template>
                </el-table-column>
                <el-table-column
                    width="100"
                    align="center"
                    label="模块"
                    style="position:relative;"
                    show-overflow-tooltip=""
                >
                    <template slot-scope="props">
                        
                        <div v-if="props.row.courseGroupId">
                            <span>{{ props.row.modelName }}</span>  
                        </div>
                    </template>
                </el-table-column>
                <el-table-column
                    width="100"
                    label="分组"
                    align="center"
                    show-overflow-tooltip
                    style="position:relative;"
                >
                    <template slot-scope="props" v-if="props.row.parentId">
                        <span>{{ props.row.groupName }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="考试/查" align="center" width="70">
                    <template slot-scope="props">
                        <span>{{ props.row.examModeName }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="学分" align="center" width="54">
                    <template slot-scope="props">
                        {{ props.row.studyScore }}
                    </template>
                </el-table-column>
                <el-table-column label="学时/周数" align="center" width="85">
                    <template slot-scope="props">
                        {{ props.row.period }}/{{
                            +props.row.weeksType == 1 ? `${props.row.weeks}周` : props.row.weeks
                        }}
                    </template>
                </el-table-column>
                <el-table-column label="是否必修" align="center" width="80">
                    <template  slot-scope="props">
                        {{ !props.row.compulsory ? '' : props.row.compulsory == '1' ? '是' : '否' }}
                    </template>
                </el-table-column>
                <el-table-column label="上机时间" align="center" width="80">
                    <template slot-scope="props">
                        <span>{{ props.row.computeTime }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="实验时数" align="center" width="80">
                    <template slot-scope="props">
                        <span>{{ props.row.experimentTime }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="学期" align="center" width="120" show-overflow-tooltip>
                    <template slot-scope="props">
                        <span>{{ props.row.semesters }}</span>
                    </template>
                </el-table-column>
            </el-table>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancel">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    getSchemeChapters,
    findCultureSchemeById,
    getTemplateById,getSchemeSchoolTerm,
    findCourseLabelRelationBySemesters
} from "common/src/api/culture/bachelor";
import courseCategoryForm from "common/src/views/culture/bachelor/courseCategoryForm";
import courseForm from "common/src/views/culture/bachelor/courseForm";
import UTILS from "common/src/utils/utils";
import { queryDic } from 'common/src/api/dictionary'
export default {
    // name: 'schemePreview',
    components: {
        courseCategoryForm,
        courseForm
    },
    props: {
        dataType: {
            default: "1", // 1为模板，2为方案
            type: String
        },
        id: {
            default: "", // 当前方案Id
            type: String
        },
        templateId: {
            default: null, // 当前方案模板Id
            type: String
        },
        schoolTerms: {
            type: Number,
            default: 0 //学期
        },
    },
    data() {
        return {
            topNavItems: [
                {
                    label: this.$t("culture.scheme.inputChaptersCn"),
                    index: 0,
                    active: true
                },
                {
                    label: this.$t("culture.scheme.inputChaptersEn"),
                    index: 1,
                    active: false
                }
            ],
            lang: "cn",
            focusIndex: 0,
            schemeInfo: {},
            schemeChapters: {},
            dic: {},
            showDic: false,
            cultureId: "",
            projId:'',
            semesterListMap:[],
            schoolTerm:'',
            copyVisible:false,
            rowData:{},
            courseTables:[],
            options: {
                types: [],
            },
            //schoolTerms:""
        };
    },
    created() {
        this.init();
        this.initSemesterListMap()
    },
    methods: {
        init() {
            const params = {};
            this.dataType =this.dataType;
            if (this.dataType == 2) {
                params.cultureId = this.id;
            } else {
                params.templateId =this.id;
                this.getTemplateInfo(params.templateId)
            }
            this.getSchemeChapters(params);
            if (this.dataType== 2) {
                this.getCultureScheme()
                let data = {
                    lang: this.$store.getters.language || 'cn',
                    type: 'allChild',
                    keys: ['X_KSLX']
                }
                queryDic(data)
                .then(res => {
                    if (res.code == 200) {
                        this.loadOptions('types', res.data.X_KSLX)
                    }
                })
                .catch(err => {
                    this.$message({
                        type: 'error',
                        message: '查询失败'
                    })
                })
            } 
        },
        loadOptions(optionKey, dataObj) {
            for (let key in dataObj) {
                if (key == 1 || key == 2) {
                    this.options[optionKey].push({
                        value: key,
                        label: dataObj[key]
                    })
                }
            }
        },
        //合并列表单元格
        arraySpanMethod({ row, column, rowIndex, columnIndex }) {
            if (row.isCategoryRow) {
                if (columnIndex == 0) {
                    return {
                        rowspan: 1,
                        colspan: 11
                    }
                } 
                else if (columnIndex !== 0) {
                    return {
                        rowspan: 0,
                        colspan: 0
                    }
                }
            }
            if (columnIndex == 2 || columnIndex == 3) {
                let spanData = columnIndex == 2 ? this.getspanData(1) : this.getspanData(2)
                let d = spanData.filter(ele => {
                    return ele.rowIndex == rowIndex
                })
                if (d.length > 0) {
                    return {
                        rowspan: d[0].rowspan,
                        colspan: 1
                    }
                }
            }
        },
        getspanData(type) {
            //type==1 分模块, type ==2 分组
            let labelId = type == 1 ? 'courseGroupId' : 'parentId'
            let curPid = -1,
                curRowIndex,
                rowspan,
                spanData = []
            this.courseTables.forEach((ele, i, arr) => {
                if (ele.isCourseRow && ele[labelId]) {
                    if (ele[labelId] != curPid) {
                        if (curPid != -1) {
                            spanData.push({
                                rowIndex: curRowIndex,
                                rowspan: rowspan
                            })
                        }
                        curPid = ele[labelId]
                        curRowIndex = i
                        rowspan = 1
                    } else {
                        spanData.push({
                            rowIndex: i,
                            rowspan: 0
                        })
                        rowspan++
                    }
                }
            })
            spanData.push({
                rowIndex: curRowIndex,
                rowspan: rowspan
            })
            return spanData
        },
        initSemesterListMap() {
            console.log(this.schemeInfo)
            if (this.dataType== 2) {
                console.log(this.dataType)
                getSchemeSchoolTerm(this.id).then(res => {
                    if (res.code == 200) {
                        let schoolTerm = 0
                        schoolTerm = res.data.schoolTerm 
                        let list = [];
                        let labelArr = ['全部','一',  '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二', '十三', '十四', '十五', '十六', '十七', '十八', '十九', '二十'];
                        for(let i = 0 ; i<= schoolTerm; i++) {
                            list.push({
                                label: labelArr[i],
                                value: i,
                                key: i,
                            })
                        }
                        this.semesterListMap = list;
                    }
                    
                })
            }
            
        },
        checkCourse(){
            this.rowData = {}
            this.courseTables = []
            if(this.schoolTerm || this.schoolTerm === 0){
                this.copyVisible = true;
                this.initSemesterListMap()
                findCourseLabelRelationBySemesters(this.id,this.schoolTerm).then(res => {
                if (res && res.code === 200) {
                    this.rowData.courseCategories =
                            res.data &&
                            res.data.coursesLabelList.map(c => {
                                //课程类型：公共学位课，必修课。。。
                                return {
                                    id: c.labelId,
                                    name: c.label,
                                    labelId: c.parentId,
                                    isElective: c.isElective,
                                    limitType: c.limitType,
                                    orderNo: c.orderNo
                                }
                            })
                        // 保存方向数据
                        this.rowData.directionList =
                            res.data && res.data.directionList.filter(e => e.directionName)
                        this.setCourseData(res.data.courseLabelRelationList)
                        this.appendCategory()
                    }
                });
            }
        },
        setCourseData(list) {
            let _this = this
            _this.rowData.courses = []
            let fn = function(value) {
                let item = _this.options.types.find(t => t.value == value)
                return item ? item.label : ''
            }
            list.forEach(ele => {
                ele.edit = false
                ele.isCourseRow = true
                ele.isGroupCheck = false
                ele.isCourseCheck = false
                ele.isModuleCheck = false
                ele.studyScore = ele.credits
                ele.semesters = ele.semesters
                ele.parentId = ele.levelType == 2 ? ele.courseGroupId : ele.parentId
                ele.courseGroupId = ele.levelType == 2 ? '' : ele.courseGroupId
                ele.examModeName = fn(ele.examMode)
                _this.rowData.courses.push(Object.assign({}, ele))
            })
        },
        appendCategory() {
            //递归树
            let ft = function(result, list) {
                result.forEach(l => {
                    let childList = list.filter(r => r.labelId == l.id)
                    while (childList.length > 0) {
                        l.children = childList
                        return ft.call(this, childList, list)
                    }
                })
                return result
            }
            //数组扁平化
            let fn = function(arr) {
                let result = []
                let line = function(arr) {
                    arr.forEach(item => {
                        result.push(item)
                        while (item.children && item.children.length > 0) return line(item.children)
                    })
                }
                line(arr)
                return result
            }
            //追加课程数据
            let addFn = function(arr) {
                let result = []
                arr.forEach(item => {
                    result.push(item)
                    if (item.hasCourse) {
                        if (this.rowData.directionList.length > 0) {
                            result = result.concat(
                                this.appendCourse(item.id),
                                this.appendDirection(item.id)
                            )
                        } else {
                            result = result.concat(this.appendCourse(item.id))
                        }
                    }
                })
                return result
            }
            let result = this.rowData.courseCategories.filter(
                l => l.labelId == '0' || l.labelId == ''
            )
            result.forEach((item, index) => {
                item.sequence = `${this.$utils.numberToChinese(index + 1)}、`
            })
            let list = fn(ft.call(this, result, this.rowData.courseCategories)).map(c => {
                return Object.assign(c, {
                    categoryName: c.name,
                    labelId: c.id,
                    isCategoryRow: true,
                    isElective: c.isElective, //是否公共选修
                    showAddCourseBtn: !c.children,
                    hasCourse: this.hasCourse(c.id)
                })
            })
            this.courseTables = addFn.call(this, list)
        },
        /**是否有课程 */
        hasCourse(labelId) {
            return this.rowData.courses.some(i => {
                return i.labelId == labelId
            })
        },
        appendDirection(key) {
            let _this = this
            let list = []
            let directionList = _.cloneDeep(_this.rowData.directionList)
            directionList.forEach((d, i) => {
                let item = {}
                item.sequence = ''
                item.categoryName = d.directionName
                item.labelId = key
                item.directionCode = d.directionCode
                item.isCategoryRow = true
                item.showAddCourseBtn = true
                item.isDirection = true
                item.hasCourse = this.rowData.courses.some(c => c.directionCode == d.directionCode)
                list.push(item)
                let childCourseList = this.rowData.courses.filter(
                    c => c.labelId == key && c.directionCode == d.directionCode
                )
                list = [...list, ...childCourseList]
            })
            return list
        },
        //添加课程项
        appendCourse(courseCategoryId, isElective = '') {
            let childCourseList = this.rowData.courses.filter(
                c => c.labelId == courseCategoryId && !c.directionCode
            )
            childCourseList.forEach(item => {
                ;(item.labelId = courseCategoryId), (item.isElective = isElective)
            })
            return childCourseList
        },
        cancel(){
            this.copyVisible = false;
        },
        getSchemeChapters(params) {
            getSchemeChapters(params).then(res => {
                if (res && res.code === 200) {
                    this.schemeChapters = res.data.map((ele, index) => {
                        ele.name =
                            UTILS.numberToChinese(index + 1) + "、" + ele.name;
                        ele.nameEn = index + 1 + "." + ele.nameEn;
                        return ele;
                    });
                }
            });
        },
        // 获取模板信息
        getCultureScheme() {
            let data = {
                id: this.id ? this.id : ""
            };
            findCultureSchemeById(data)
                .then(res => {
                    if (res && res.code === 200) {
                        this.schemeInfo = res.data;
                        this.projId = res.data.projId;
                        let title=res.data.grade+'级'+'  '+res.data.trainingCategoryI18n+'  '+res.data.facultyI18n+'  '+res.data.campusProfessionName+'('+res.data.campusProfession+')';
                        this.schemeInfo.title=title;
                    }
                })
                .catch(e => {
                    this.$message({
                        type: "error",
                        message: "查询培养方案信息失败"
                    });
                });
        },
        clickItem(item) {
            this.lang = item.index === 0 ? "cn" : "en";
            this.topNavItems.forEach(nav => {
                nav.active = false;
            });
            item.active = true;
            this.focusIndex = item.index;
        },
        exportPdf() {
            let path =
                "/api/cultureservice/bclCultureScheme/exportCultureSchemePdf?id=" +
                    this.id +
                    "&x-token=" +
                    (this.$store.state.session.sessionid ||
                localStorage.getItem("sessionid") ||
                "") + "&language=" + this.$store.getters.language;
            window.open(path);
        },
        exportDoc() {
            let path =
                "/api/cultureservice/bclCultureScheme/exportCultureScheme?id=" +
                    this.id +
                    "&x-token=" +
                    (this.$store.state.session.sessionid ||
                localStorage.getItem("sessionid") ||
                "") + "&language=" +  this.$store.getters.language;
            window.open(path);
        },
        back(){
            this.$router.go(-1);//返回上一层
        },
        // 获取模板信息
        getTemplateInfo(id) {
            console.log(id)
            getTemplateById(id)
                .then(res => {
                    if (res.code === 200) {
                        this.schemeInfo = res.data;
                        this.projId = res.data.projId
                        // this.schoolTerms = res.data.schoolTerm
                        console.log(this.schoolTerms)
                    }
                })
                .catch(e => {
                    this.$message({
                        type: "error",
                        message: "查询培养方案模板信息失败"
                    });
                });
        }
    }
};
</script>

<style lang="scss" scoped>
.edu-page-title {
    border-bottom: 2px solid rgba(210, 212, 214, 1);
    span {
        cursor: pointer;
        display: inline-block;
        padding-right: 10px;
    }
    span.active {
        color: #2876c2;
    }
    button{
        margin-bottom: 15px;
    }
}

.border-right {
    margin-right: 10px;
}
.check-course{
    position: absolute;
    top:0;
    right:7px;
}
</style>
